package com.broada.apm.indicator.api.impl;

import java.util.Map;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;

import com.broada.apm.indicator.api.PersistanceService;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.utils.EsClientUtil;
import com.broada.apm.utils.JsonUtil;

public class PersistanceServiceImpl implements PersistanceService {
	
	private Client client = EsClientUtil.getTransportClient();

	@Override
	public void saveObject(String index, String type, Map<String, Object> object) throws ApmDataIndicatorException {
		try {
			BulkRequestBuilder bulkbuilder = client.prepareBulk();
			for (Map.Entry<String, Object> entity : object.entrySet()) {
				String id = entity.getKey();
				Object obj = entity.getValue();
				bulkbuilder.add(client.prepareIndex(index, type, id).setSource(JsonUtil.obj2json(obj)));
			}
			BulkResponse bulkResponse = bulkbuilder.setRefresh(true).execute().actionGet();
			if (bulkResponse.hasFailures())
				throw new ApmDataIndicatorException(String.format("对象组保存失败:%s", bulkResponse.buildFailureMessage()));
		} catch (Exception e) {
			throw new ApmDataIndicatorException(e);
		}
	}
}